package com.olap.starter.common.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.olap.starter.util.sql.MysqlTaleSqlService;
import com.olap.starter.util.sql.OracleTaleSqlService;
import com.olap.starter.util.sql.SqlServerTaleSqlService;
import com.olap.starter.util.sql.TaleSqlService;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * sql 工具类
 */
public class TaleSqlUtil {
    private static final Map<String, TaleSqlService> sqlMap = new HashMap<>();

    static {
        sqlMap.put(DbType.ORACLE.getDb(), new OracleTaleSqlService());
        sqlMap.put(DbType.MYSQL.getDb(), new MysqlTaleSqlService());
        sqlMap.put(DbType.SQL_SERVER.getDb(),  new SqlServerTaleSqlService());
    }

    public static String getTablesSql(JdbcTemplate jdbcTemplate) {
        String dbType = SqlUtils.getDbType(jdbcTemplate);
        return getTablesSql(getTableName(jdbcTemplate), dbType);
    }

    public static String getTableName(JdbcTemplate jdbcTemplate){
        String dbType = SqlUtils.getDbType(jdbcTemplate);
        String dbName = null;
        if (dbType.equals(DbType.ORACLE.getDb())) {
            dbName = jdbcTemplate.queryForObject("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL", String.class);
        } else if (dbType.equals(DbType.MYSQL.getDb())) {
            dbName = jdbcTemplate.queryForObject("SELECT DATABASE()", String.class);
        }else if (dbType.equals(DbType.SQL_SERVER.getDb())) {
            dbName = jdbcTemplate.queryForObject("SELECT DB_NAME()", String.class);
        } else {
            throw new RuntimeException("不支持数据库类型！");
        }
        return dbName;
    }
    public static String getTablesSql(String dbName, String dbType) {
        if(sqlMap.get(dbType) == null){
            throw new RuntimeException("不支持数据库类型！");
        }
        return sqlMap.get(dbType).getTablesSql(dbName);
    }

    public static String getColumnsSql(String dbName, String tableName, JdbcTemplate jdbcTemplate) {
        String dbType = SqlUtils.getDbType(jdbcTemplate);
        return getColumnsSql(dbName, tableName, dbType);
    }

    public static String getColumnsSql(String dbName, String tableName, String dbType) {
        return sqlMap.get(dbType).getColumnsSql(dbName, tableName);
    }
}
